package com.tianqu.tms.www.cardect.controller;

import java.util.List;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.entity.TmsDetectInfo;
import com.tianqu.tms.entity.TmsDetectNormal;
import com.tianqu.tms.entity.TmsDetectPic;
import com.tianqu.tms.entity.TmsDetectSenior;

/***
 * 
 * 待确认重新检测Controller
 * 
 * @author tianshifu
 * 
 */
public class CarSConfirmToDectoverResultController extends TmsController {
	private Logger logger = Logger
			.getLogger(CarSConfirmToDectoverResultController.class);// log
	private static final String CARSERIAL = "carSerial";// 车辆ID
	private static final String SAVE_STATUS = "status";// 保存状态

	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = TxController.getTxController();

		// 添加事务提交异常捕获
		try {
			controller.begin();
			// 从uc中获取车辆ID，根据车辆ID查询检测报告ID，删除检测报告信息，并更新基本信息表数据，将状态改为2
			String carSerial = (String) uc.getAttribute(CARSERIAL);// 从uc中获取车辆ID
			String status = (String) uc.getAttribute(SAVE_STATUS);
			uc.removeAttribute(SAVE_STATUS);
			// 根据车辆ID查询出车辆检测ID
			TmsDetectInfo carEntity = TmsDetectInfo.getInstance();
			carEntity = carEntity.getWDIpadCarInfoBySerial(carSerial, 1);

			int carDetectId = carEntity.getCarDetectId();// 车辆检测ID

			int chkModel = carEntity.getChkModel();// 检测模式

			if (chkModel == 1)// 普通检测模式
			{
				// 删除检测信息
				TmsDetectNormal normalEntity = TmsDetectNormal.getInstance();
				normalEntity.setId(carDetectId);
				normalEntity.delDetectNormal(normalEntity);// 删除检测信息
			}
			if (chkModel == 2)// 高级检测模式
			{
				TmsDetectSenior seniorEntity = TmsDetectSenior.getInstance();
				seniorEntity.delTisDetectSenior(carDetectId);// 删除高级检测信息
			}
			TmsUserProfile profile = uc.getUserProfile();
			// 更新基本信息表信息，将基本检测信息表中的检测报告信息置空
			carEntity.resetCarInfoByIdAndStatus(carSerial, Integer
					.parseInt(status), profile.getUniqueId());// 根据车辆ID和车辆状态还原基本信息表信息

			// 删除图片信息
			// 现在图片表中查该检测报告是否有图片信息，有的话直接删除
			TmsDetectPic picEntity = TmsDetectPic.getInstance();
			List<TmsDetectPic> picList = picEntity
					.findDetectPicInfoByDetectId(carDetectId);// 车辆整体图片

			if (picList.size() > 0) {
				// 根据检测ID删除图片信息
				picEntity.delPic(carDetectId);
			}
			controller.commit();
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}

		logger.debug(this.getClass().getName() + "#doAction was completed.");
	}

}
